package zuo.algo.c03;

import zuo.algo.util.SortUtils;

import java.util.Arrays;

/**
 * 00:34-归并排序
 */
public class MergeSort {

    public static void sort(int[] arr) {
        sort(arr, 0, arr.length - 1);
    }

    public static void sort(int[] arr, int begin, int end) {
        if (end <= begin) {
            return;
        }
        int mid = begin + (end - begin) / 2;
        sort(arr, begin, mid);
        sort(arr, mid + 1, end);
        merge(arr, begin, mid, end);
    }

    private static void merge(int[] arr, int begin, int mid, int end) {
        int tempLen = end - begin + 1;
        int[] tempArr = new int[tempLen];
        int idx = 0, idx1 = begin, idx2 = mid + 1;
        while (idx1 <= mid && idx2 <= end) {
            if (arr[idx1] <= arr[idx2]) {
                tempArr[idx++] = arr[idx1++];
            } else {
                tempArr[idx++] = arr[idx2++];
            }
        }
        while (idx1 <= mid) {
            tempArr[idx++] = arr[idx1++];
        }
        while (idx2 <= end) {
            tempArr[idx++] = arr[idx2++];
        }
        for (idx = 0; idx < tempLen; idx++) {
            arr[begin+idx] = tempArr[idx];
        }
    }

    public static void main(String[] args) {
        int maxLen = 100000;
        for (int i = 0; i < 100000; i++) {
            int[] arr1 = SortUtils.getRandomArr(maxLen);
            int[] arr2 = Arrays.copyOf(arr1, arr1.length);
            sort(arr1);
            Arrays.sort(arr2);
            SortUtils.assertArr(arr1, arr2);
            System.out.println(i);
        }
    }
}
